package com.itheima.service.mongo.Impl;

import cn.hutool.core.collection.CollectionUtil;
import com.itheima.domain.mongo.*;
import com.itheima.domain.vo.PageBeanVo;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import org.apache.dubbo.config.annotation.DubboService;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.ArrayList;
import java.util.List;

@DubboService
public class MovementServiceImpl implements MovementService {
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisIdService redisIdService;

    @Override
    public void saveMovement(Movement movement) {
        //1.往动态表中存
        Long pid = redisIdService.getNextId(ConstantUtil.MOVEMENT_ID);
        //不用数据库产生的 , 这样下面也可以用了
//        movement.setId(ObjectId.get());
        movement.setPid(pid);
        movement.setSeeType(1);//TODO 开发中修改
        movement.setCreated(System.currentTimeMillis());
        mongoTemplate.save(movement, ConstantUtil.MOVEMENT_ID);
        //2.往个人动态表中存id
        MyMovement myMovement = new MyMovement();
//        myMovement.setId(movement.getId());
        myMovement.setPublishId(movement.getId());
        myMovement.setCreated(movement.getCreated());

        mongoTemplate.save(myMovement, ConstantUtil.MOVEMENT_MINE + movement.getUserId());
        //3.查询好友关系(从好友关系大表查询)
        Query query = new Query(
                Criteria.where("userId").is(movement.getUserId())
        );
        List<Friend> friends = mongoTemplate.find(query, Friend.class);

        //4.往好友动态表中存我的动态的id
        if (CollectionUtil.isNotEmpty(friends)) {
            for (Friend friend : friends) {
                System.out.println(friend);
                FriendMovement friendMovement = new FriendMovement();
                friendMovement.setPublishId(movement.getId());
                friendMovement.setCreated(movement.getCreated());
                friendMovement.setUserId(movement.getUserId());
                mongoTemplate.save(friendMovement, ConstantUtil.MOVEMENT_FRIEND + friend.getFriendId());
            }
        }
    }

    @Override
    public PageBeanVo findMyMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        //从自己的动态表中获得发表的动态的id
        System.out.println("userId"+userId);
        int starIndex = (pageNum - 1) * pageSize;
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(starIndex).limit(pageSize);

        List<MyMovement> myMovements = mongoTemplate.find(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

        List<Movement> movementList = new ArrayList<>();
        for (MyMovement myMovement : myMovements) {
            Movement byId = mongoTemplate.findById(myMovement.getPublishId(), Movement.class);
            System.out.println(byId);
            if (byId.getSeeType() == 1) {
                movementList.add(byId);
            }
        }
        //查询总数
        long count = mongoTemplate.count(query, MyMovement.class, ConstantUtil.MOVEMENT_MINE + userId);

        return new PageBeanVo(pageNum, pageSize, count, movementList);
    }

    @Override
    public PageBeanVo findFriendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        int starIndex = (pageNum - 1) * pageSize;
        Query query = new Query().with(Sort.by(Sort.Order.desc("created"))).skip(starIndex).limit(pageSize);
        //先从好友关系表中找到自己的朋友集合
        List<FriendMovement> friendMovements = mongoTemplate.find(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);
        List<Movement> movementArrayList = new ArrayList<>();
        for (FriendMovement friendMovement : friendMovements) {
            Movement movementFriend = mongoTemplate.findById(friendMovement.getPublishId(), Movement.class);
            movementArrayList.add(movementFriend);

        }

        long count = mongoTemplate.count(query, FriendMovement.class, ConstantUtil.MOVEMENT_FRIEND + userId);
        return new PageBeanVo(pageNum, pageSize, count, movementArrayList);
    }

    @Override
    public PageBeanVo findRecommendMovementByPage(Long userId, Integer pageNum, Integer pageSize) {
        int starIndex = (pageNum - 1) * pageSize;
        Query query = new Query(Criteria.where("userId")
                .is(userId))
                .skip(starIndex)
                .with(Sort.by(Sort.Order.desc("created")));

        List<RecommendMovement> recommendMovements = mongoTemplate.find(query, RecommendMovement.class);
        ArrayList<Movement> list = new ArrayList<>();
        for (RecommendMovement recommendMovement : recommendMovements) {
            ObjectId publishId = recommendMovement.getPublishId();
            Movement byId = mongoTemplate.findById(publishId, Movement.class);

            if (byId.getSeeType() == 1) {
                list.add(byId);
            }

        }
        long count = mongoTemplate.count(query, RecommendMovement.class);

        return new PageBeanVo(pageNum, pageSize, count, list);
    }

    @Override
    public Movement findById(ObjectId id) {
        System.out.println("findbyObjectId"+id);
        return mongoTemplate.findById(id, Movement.class);
    }

    @Override
    public PageBeanVo findMyMovementByPage(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        int starIndex= (pageNum-1)*pageSize;
        Query query = new Query()
                .with(Sort.by(Sort.Order.desc("created")))
                .skip(starIndex).limit(pageSize);
        if (userId!=null){
            query.addCriteria(Criteria.where("userId").is(userId));
        }
        if (state!=null){
            query.addCriteria(Criteria.where("state").is(state));
        }
        List<Movement> movementList = mongoTemplate.find(query, Movement.class);
        long count = mongoTemplate.count(query, Movement.class);
        return new PageBeanVo(pageNum,pageSize,count,movementList);

    }

    @Override
    public void updateMovement(Movement movement) {
        mongoTemplate.save(movement);
    }


}
